﻿@using HP.HPTRIM.Service
@using ServiceStack;
@using HP.HPTRIM.ServiceModel;
@inherits SecureViewPage

@{
    ViewBag.Title = "Copy Record Document Example";

    var recordTypes = this.TrimHelper.Search<RecordType>(
        BaseObjectTypes.RecordType,
        "behaviour:document",
        pageSize: 100, properties: new string[] { "Name" });



}

<form id="bulk-upload" style="margin-left:10px;">

    <fieldset>

        <label>Record Type:</label>
        <select name="@PropertyIds.RecordRecordType">
            @foreach (var recordType in recordTypes)
            {
                <option value="@recordType.Uri">@recordType.Name</option>
            }
        </select>

        <legend>Upload multiple files</legend>
        <label>Title:</label>
        <input name="@PropertyIds.RecordTitle" /><br />

        <input id="files" type="file" multiple /><br />
    </fieldset>
    <button class="btn" type="submit">Upload</button>
</form>

@section scripts {
    <script>
    $(document).ready(function () {
        var uris = [];
        var fileCount;
        var doSubmit = function (formData, fileName) {

            var request = new XMLHttpRequest();

            // when a file upload is complete add the URI to the list of 
            // newly created records.  When the last file is uploaded re-direct 
            // to a search result of the newly created records
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    var response = JSON.parse(request.responseText);
                    if (request.status == 200) {                       

                        for (var rec_idx = 0; rec_idx < response.Results.length; rec_idx++) {
                            uris.push(response.Results[rec_idx].Uri);
                        }

                        if (uris.length == fileCount) {
                            window.location = "record?q=uri:" + uris.join();
                        }
                    }

                    if (request.status == 500) {
                        fileCount--;
                        alert("Error uploading " + fileName + ". " + response.ResponseStatus.Message);
                    }
                }
            };

            request.open("POST", "record?format=json");
            request.send(formData);

        }

        $('#bulk-upload').submit(function () {
            uris = [];

            if (!window.File) {
                alert('Sorry, your browser doesn\'t support the File API so last modified date will not be available');
                return false;
            } else {
                var fileEl = $('#files')[0];
                if (fileEl.files.length > 0) {
                    if (typeof fileEl.files[0].lastModifiedDate === 'undefined') {
                        alert('Sorry, your browser doesn\'t support the lastModifiedDate property so last modified date will not be available');
                        return false;
                    } else {
                        try {
                            var uris = [];
                            fileCount = fileEl.files.length;
                            for (var idx = 0; idx < fileEl.files.length; idx++) {                                

                                var file = fileEl.files[idx];

                                // 4Mb is the ASP.Net default file upload max
                                // do a search for maximum request length exceeded to find out how to increase this limit.
                                if (file.size > 4000000) {
                                    if (confirm("the file " + file.name + " is too large to upload, do you wish to proceed without it?")) {
                                        fileCount--;
                                        continue;
                                    } else {
                                        break;
                                    }
                                }

                                //adjust the title field
                                var nm = file.name;
                                var data = {};
                                $(this).find(':input').each(
                                    function (i, formInput) {
                                        var inputVal = this.value;
                                        if (this.name === "RecordTitle") {
                                            inputVal = nm + ' (' + inputVal + ')';
                                        }
                                        data[this.name] = inputVal;
                                    });

                                var lmDate = file.lastModifiedDate;

                                var formData = new FormData();
                                // set the date created to the file last modified date
                                // otherwise date created will always be now
                                formData.append("RecordDateCreated", lmDate.toISOString());
                                formData.append("Files", file);

                                for (var key in data) {
                                    formData.append(key, data[key]);
                                }

                                doSubmit(formData, nm);
                            }
                        } catch (ex) {
                            alert(ex);
                        }
                    }
                }
            };
            return false;
        });
    });
    </script>
}
